from flask import session, current_app
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db, models
import logging

# manage.py作为项目入口文件 单一职责的原则

# 传入不同配置名称获取到不同配置的app
from info.models import User

app = create_app("development")
# 创建管理对象
manager = Manager(app)
# 创建迁移对象  app=None, db=None, directory='migrations'
migrate = Migrate(app, db)
# 添加迁移指令到manager管理对象
# command = args[0] name = args[1]
manager.add_command("db", MigrateCommand)

@manager.option("-n", "-name", dest="name")
@manager.option("-p", "-password", dest="password")
def createsurperuser(name, password):
    """
    创建后台管理员
    使用方式：
        python manage.py createsurperuser -p "密码" -n "账户名"
    """

    if not all([name, password]):
        print("参数不完整")
        return

    # 创建用户对象
    surperuser = User()
    surperuser.nick_name = name
    surperuser.mobile = name
    surperuser.password = password
    # 标示改用户是后端管理员
    surperuser.is_admin = True

    try:
        db.session.add(surperuser)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)

    print("创建后台管理员成功")



if __name__ == '__main__':
    manager.run()
